package com.algorithm;

import java.util.Arrays;
/**
 * 冒泡排序
 * 相邻两个数比较，直到将最大(小)的数放置最后面
 * @author Administrator
 *
 */
public class BubbleSort {

    public static int[] sort(int[] sourceArray){
    	//数组拷贝;
    	int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
    	for(int i=1;i<arr.length;i++) {
    		boolean flag = true;
    		for(int j=0;j<arr.length-i;j++) {
    			if(arr[j]>arr[j+1]) {
    				int temp = arr[j];
    				arr[j]=arr[j+1];
    				arr[j+1]=temp;
    				//还需要排序
    				flag = false;
					System.out.println("排序中:"+Arrays.toString(arr));
    			}
    		}

    		if(flag) {//已排好序
    			break;
    		}

    	}

        return arr;
    }


	public static int[] sort2(int[] sourceArray) {
    	int[] arr = Arrays.copyOf(sourceArray,sourceArray.length);
    	for(int i=0;i<arr.length-1;i++){
    		boolean flag = false;
    		for(int j=1;j<arr.length-i;j++){
				if(arr[j]<arr[j-1]){
					int temp = arr[j];
					arr[j]=arr[j-1];
					arr[j-1] = temp;
					flag = true;
				}
			}
			System.out.println("sort2排序中:"+Arrays.toString(arr));
    		if(!flag){
    			return arr;
			}
		}
		return arr;
	}

	public static int[] sort3(int[] source){
    	int[] arr = Arrays.copyOf(source,source.length);
    	for(int i=1;i<arr.length;i++){
    		boolean flag = false;
    		for(int j=1;j<arr.length-(i-1);j++){
    			if(arr[j]<arr[j-1]){
    				int temp = arr[j];
    				arr[j] = arr[j-1];
    				arr[j-1] = temp;
					flag = true;
				}
			}
    		if(!flag){
    			return arr;
			}
			System.out.println("sort3排序中:"+Arrays.toString(arr));
		}
    	return arr;
	}

	public static int[] sort4(int[] arrSource){
		int[] arr = Arrays.copyOf(arrSource,arrSource.length);
		for(int i=0;i<arr.length-1;i++){
			boolean flag = false;
			for(int j=1;j<arr.length-i;j++){
				if(arr[j]<arr[j-1]){
					int temp = arr[j];
					arr[j] = arr[j-1];
					arr[j-1] = temp;
					flag = true;
				}
			}
			System.out.println("sort4排序中:"+Arrays.toString(arr));
			if(!flag){
				return arr;
			}
		}
		return arr;
	}
    public static void main(String[] args){

    	int[] sort = new int[]{8,9,10,3,2,4,5,6,7,1};
    	System.out.println("排序前:"+Arrays.toString(sort));
    	System.out.println("排序后:"+Arrays.toString(sort4(sort)));

	}
}
